//
//  HomePageViewController.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/2.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "HomePageViewController.h"
#import "SystemNotificationListViewController.h"
#import "AdScrollView.h"
#import "CityPostionExtViewController.h"
#import "DistrictView.h"
#import "Utils.h"
#import "SystemNoticeModel.h"
#import "SystemNotificationTableViewCell.h"
#import "InfoDetailViewController.h"
#import "FlashNewModel.h"
#import "NewsInfoTableViewCell.h"
#import "MyInfoModel.h"
#import "HomeAllNewInfoTableViewCell.h"
#import "HomeAllSystemNoticeTableViewCell.h"
#import "AllNoticeModel.h"

#import "UIImageView+WebCache.h"

#import "HomePageSectionHeaderCellTableViewCell.h"
#import "BuaatVolunteerServerSDK.h"
#import "HomeWebViewController.h"
#import "MJRefresh.h"
@interface HomePageViewController ()<UITableViewDataSource,UITableViewDelegate,CityPositionExtViewControllerDelegate,DistrictViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,AdScrollViewDelegate,MJRefreshBaseViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(strong,nonatomic)MJRefreshHeaderView *mjRefreshHeaderView;
/*
 0 全部
 1 系统通知
 2 快讯播报
 3 我的信息
 */
@property(assign,nonatomic)int tag;
@property(strong,nonatomic)NSArray *keys;
@property(strong,nonatomic)NSDictionary *data;
//全部
@property(strong,nonatomic)NSArray *allData;
//系统通知
@property(strong,nonatomic)NSDictionary *systemNotificationData;
//快讯播报
@property(strong,nonatomic)NSDictionary *flashNewData;
//我的信息
@property(strong,nonatomic)NSDictionary *myInfoData;

@property(strong,nonatomic)AdScrollView *adScrollView;

@property(strong,nonatomic)NSString *positionState;

@property(strong,nonatomic)DistrictView *districtView;

//自动定位
@property(strong,nonatomic)BMKLocationService *locService;
@property(strong,nonatomic)BMKGeoCodeSearch *geoCodeSearch;
@property(strong,nonatomic)NSDictionary *positionCitys;
@property(assign,nonatomic)BOOL isNeedShowPositionResult;


@property(strong,nonatomic)NSString *state;
//all system news myInfo none
@property(strong,nonatomic)NSString *refreshType;

@property(assign,nonatomic)BOOL isFirst;

@property(strong,nonatomic)NSString *netAdState;
@end

@implementation HomePageViewController
-(void)dealloc{
    [self.locService stopUserLocationService];
    self.locService=nil;
    self.geoCodeSearch.delegate=nil;
    self.geoCodeSearch=nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    for(int i=0;i<4;i++){
        UIButton *button=(UIButton *)[self.headerView viewWithTag:100+i];
        button.titleLabel.font=[UIFont systemFontOfSize:15.0f*SCREEN_WIDTH/320];
    }
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    self.title=@"首页";
    
    UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:@"城市" style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
    self.navigationItem.leftBarButtonItem=leftBarButton;
    
    [self startUpdatingLocation];
    
    
//    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithTitle:@"退出" style:UIBarButtonItemStyleBordered target:self action:@selector(chickRightBarButton:)];
//    self.navigationItem.rightBarButtonItem=rightBarButton;
    
    
    AdScrollView *adScrollView=[[AdScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH,SCREEN_WIDTH*3/10)];
    adScrollView.data=@[@{@"image":@"guanggao_4.jpg"},@{@"image":@"guanggao_0.jpg"},@{@"image":@"guanggao_1.jpg"},@{@"image":@"guanggao_2.jpg"},@{@"image":@"guanggao_3.jpg"},@{@"image":@"guanggao_4.jpg"},@{@"image":@"guanggao_0.jpg"}];
    self.adScrollView=adScrollView;
    self.adScrollView.delegate=self;
    
    self.tableView.dataSource=self;
    self.tableView.delegate=self;
    self.tableView.tableHeaderView=self.adScrollView;
    
    UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3)];
    self.tableView.tableFooterView=footerView;
    
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    self.mjRefreshHeaderView=header;
    header.delegate=self;
    header.scrollView = self.tableView;
    
    self.tag=1;
    [self.tableView registerNib:[UINib nibWithNibName:@"SystemNotificationTableViewCell" bundle:nil] forCellReuseIdentifier:@"SystemNotificationTableViewCellIdentifier"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"FlashNewTableViewCellIdentifier"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeAllNewInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"HomeAllNewInfoTableViewCellIdentifier"];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeAllSystemNoticeTableViewCell" bundle:nil] forCellReuseIdentifier:@"HomeAllSystemNoticeTableViewCellIdentifier"];

    [self.tableView registerNib:[UINib nibWithNibName:@"HomePageSectionHeaderCellTableViewCell" bundle:nil] forCellReuseIdentifier:@"HomePageSectionHeaderCellTableViewCellIdentifier"];
//    [self.tableView registerClass:[TableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"HeaderCellIdentifier"];
    self.tag=0;
//    self.allData=@[[SystemNoticeModel new],[SystemNoticeModel new],[FlashNewModel new],[FlashNewModel new]];
    self.state=@"0";
    self.netAdState=@"0";
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleTableViewContent:) name:NotificationLoginOut object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshTableViewContent:) name:NotificationLoginChangeInfo object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userPositionDidChange:) name:NotificationUserPositionDidChange object:nil];

    
    [self loadAllData];
    
    self.isFirst=YES;
    //加载广告
    [self netLoadAd];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.isFirst==NO){
        [self loadAd];
    }
    self.isFirst=NO;
}

-(void)viewWillDisappear:(BOOL)animated{
    [SVProgressHUD dismiss];
    [self.mjRefreshHeaderView endRefreshing];
    self.state=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
    self.districtView.hidden=YES;
}

#pragma mark - 广告
-(void)loadAd{
    NSString *appRefreshAdDateStr=[[NSUserDefaults standardUserDefaults]valueForKey:KAppRefreshDateStr_Home];
    NSDateFormatter *f=[[NSDateFormatter alloc]init];
    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *appRefreshAdDate=[f dateFromString:appRefreshAdDateStr];
    if(![Utils isCurrentDay:appRefreshAdDate]||appRefreshAdDateStr.length==0){
        //刷新
        [self netLoadAd];
        
    }else{
        //不刷新
    }
}

-(void)netLoadAd{
    ModelUser *modeluser = [UserInfoManager sharedManager].modelMser;
    NSString *tempState=[NSString stringWithFormat:@"%d",[self.netAdState intValue]+1];
    self.netAdState=[NSString stringWithFormat:@"%@",tempState];
    __weak HomePageViewController *this=self;
    
    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Home];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[BuaatVolunteerServerSDK sharedInstance]requestAdvertEnquiryWithVolunteerCode:modeluser.volunteerCode module:@"home" location:[[NSUserDefaults standardUserDefaults]valueForKey:KUserPosition] success:^(NSHTTPURLResponse *response, id responseObject) {
        if(this){
            if([this.netAdState isEqualToString:tempState]){
                NSArray *resultArr=responseObject[@"result"];
                if([resultArr isKindOfClass:[NSArray class]]){
                    if(resultArr.count!=0){
                        [resultArr sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];
                        NSMutableArray *arrM=[NSMutableArray array];
                        NSDictionary *d=[resultArr lastObject];
                        [arrM addObject:@{@"image":d[@"adImg"],@"link":d[@"adLink"]}];
                        for(int i=0;i<resultArr.count;i++){
                            NSDictionary *dic=resultArr[i];
                            [arrM addObject:@{@"image":dic[@"adImg"],@"link":dic[@"adLink"]}];
                        }
                        d=resultArr[0];
                        [arrM addObject:@{@"image":d[@"adImg"],@"link":d[@"adLink"]}];
                        
                        this.adScrollView.data=arrM;
                    }
                    
                    NSDateFormatter *f=[[NSDateFormatter alloc]init];
                    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSString *dateStr=[f stringFromDate:[NSDate date]];
                    [[NSUserDefaults standardUserDefaults]setObject:dateStr forKey:KAppRefreshDateStr_Home];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }else{
                    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Home];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }

            }
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Home];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    
}

#pragma mark 退出删除数据
-(void)deleTableViewContent:(NSNotification *)sender
{
    self.myInfoData = @{};
    if (self.tag==3) {
        self.keys = @[];
        [self.tableView reloadData];
    }
    
}
-(void)refreshTableViewContent:(NSNotification *)sender
{
    self.myInfoData = @{};
    if (self.tag==3) {
        self.keys = @[];
        [self loadMyInfoData];
    }
}

-(void)chickRightBarButton:(UIBarButtonItem *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)chickHeaderButton:(id)sender {
    UIButton *selectedButton=sender;
    
    for(int i=0;i<4;i++){
        UIButton *button=(UIButton *)[self.headerView viewWithTag:100+i];
        UIView *view=[self.headerView viewWithTag:200+i];
        if(button==selectedButton){
            button.selected=YES;
            view.hidden=NO;
        }else{
            button.selected=NO;
            view.hidden=YES;
        }
        
    }
    self.tag=selectedButton.tag-100;
    
    switch (self.tag) {
        case 0:{
            //全部
            [self loadAllData];
        }
            break;
        case 1:{
            //系统通知
            [self loadSystemNoData];
        }
            break;
        case 2:{
            //快讯播报
            [self loadFlashNewData];
        }
            break;
        case 3:{
            //我的信息
            [self loadMyInfoData];
        }
            break;
        default:
            break;
    }
    
    
    
}

//加载全部信息
-(void)loadAllData{
    if([self.refreshType isEqualToString:@"all"]){
        return;
    }
    [self.mjRefreshHeaderView endRefreshing];
    self.refreshType=@"all";
    if(self.allData.count==0){
        self.keys=@[@""];
        
        [SVProgressHUD show];
        NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
        self.state=[NSString stringWithFormat:@"%@",tempState];
        __weak HomePageViewController *this=self;
        [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerNoticeAllNewsWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD dismiss];
                    NSMutableArray *allData=[NSMutableArray array];
                    
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *resultArr = responseObject[@"result"];
                        if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                            if(resultArr.count!=0){
                                for(int i=0;i<resultArr.count;i++){
                                    NSDictionary *dic=resultArr[i];
                                    int msgTypeInt=[dic[@"msgType"] intValue];
                                    if(msgTypeInt==1){
                                        //系统通知
                                        SystemNoticeModel *model=[SystemNoticeModel getClassForDic:dic];
                                        if(![model.createDate isKindOfClass:[NSNull class]]&&model.createDate.length!=0){
                                            model.createDate=[NSString stringWithFormat:@"%@-%@-%@",[model.createDate substringWithRange:NSMakeRange(0, 4)],[model.createDate substringWithRange:NSMakeRange(4, 2)],[model.createDate substringWithRange:NSMakeRange(6, 2)]];
                                            
                                        }
                                        [allData addObject:model];
                                    }else if (msgTypeInt==2){
                                        //快讯播报
                                        FlashNewModel *model=[FlashNewModel getClassForDic:dic];
                                        if(![model.createDate isKindOfClass:[NSNull class]]&&model.createDate.length!=0){
                                            model.createDate=[NSString stringWithFormat:@"%@-%@-%@",[model.createDate substringWithRange:NSMakeRange(0, 4)],[model.createDate substringWithRange:NSMakeRange(4, 2)],[model.createDate substringWithRange:NSMakeRange(6, 2)]];
                                            
                                        }
                                        [allData addObject:model];
                                    }
                                }
                            }

                            
                        }
                    }
                    
                    this.allData=allData;
//                    [this.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
                    this.tableView.contentOffset=CGPointMake(0, 0);
                    [this.tableView reloadData];
                }
                
            }

        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD showErrorWithStatus:@"网络错误"];
                }
            }
        }];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }else{
        self.keys=@[@""];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }
    
}

-(void)loadMoreAllData{
    self.refreshType=@"all";

    [SVProgressHUD dismiss];
    
    //responseData
    NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
    self.state=[NSString stringWithFormat:@"%@",tempState];
    __weak HomePageViewController *this=self;
    [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerNoticeAllNewsWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                NSMutableArray *allData=[NSMutableArray array];
                
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSArray *resultArr = responseObject[@"result"];
                    if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                        
                        
                        if(resultArr.count!=0){
                            for(int i=0;i<resultArr.count;i++){
                                NSDictionary *dic=resultArr[i];
                                int msgTypeInt=[dic[@"msgType"] intValue];
                                if(msgTypeInt==1){
                                    //系统通知
                                    SystemNoticeModel *model=[SystemNoticeModel getClassForDic:dic];
                                    if(![model.createDate isKindOfClass:[NSNull class]]&&model.createDate.length!=0){
                                        model.createDate=[NSString stringWithFormat:@"%@-%@-%@",[model.createDate substringWithRange:NSMakeRange(0, 4)],[model.createDate substringWithRange:NSMakeRange(4, 2)],[model.createDate substringWithRange:NSMakeRange(6, 2)]];
                                        
                                    }
                                    [allData addObject:model];
                                }else if (msgTypeInt==2){
                                    //快讯播报
                                    FlashNewModel *model=[FlashNewModel getClassForDic:dic];
                                    if(![model.createDate isKindOfClass:[NSNull class]]&&model.createDate.length!=0){
                                        model.createDate=[NSString stringWithFormat:@"%@-%@-%@",[model.createDate substringWithRange:NSMakeRange(0, 4)],[model.createDate substringWithRange:NSMakeRange(4, 2)],[model.createDate substringWithRange:NSMakeRange(6, 2)]];
                                        
                                    }
                                    [allData addObject:model];
                                }
                            }
                        }

                        
                    }
                }
                this.allData=allData;
                [this.tableView reloadData];
                this.refreshType=@"none";
                
            }
            
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                [SVProgressHUD showErrorWithStatus:@"网络错误"];
                this.refreshType=@"none";
                
            }
        }
    }];
}

//加载系统通知
-(void)loadSystemNoData{
    if([self.refreshType isEqualToString:@"system"]){
        return;
    }
    [self.mjRefreshHeaderView endRefreshing];
    self.refreshType=@"system";
    if([self.systemNotificationData allKeys].count==0){
        [SVProgressHUD show];
        //responseData
        NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
        self.state=[NSString stringWithFormat:@"%@",tempState];
        __weak HomePageViewController *this=self;
        [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerSystemNoticeWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD dismiss];
                    NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                    
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *resultArr = responseObject[@"result"];
                        if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                            
                            if(resultArr.count!=0){
                                
                                for(int i=0;i<resultArr.count;i++){
                                    SystemNoticeModel *model=[SystemNoticeModel getClassForDic:resultArr[i]];
                                    if(dicM[model.createDate]==nil){
                                        NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                        [dicM setObject:arrM forKey:model.createDate];
                                    }else{
                                        NSMutableArray *arrM=dicM[model.createDate];
                                        [arrM addObject:model];
                                    }
                                }
                            }
                        }
                    }
                    
//                    if([responseObject isKindOfClass:[NSArray class]]){
//                        NSArray *resultArr=responseObject;
                    

//                    }
                    this.systemNotificationData=dicM;
                    this.keys=[[this.systemNotificationData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
                    this.tableView.contentOffset=CGPointMake(0, 0);
//                    [this.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
                    [this.tableView reloadData];
                    this.refreshType=@"none";
                    
                }
            }

        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD showErrorWithStatus:@"网络错误"];
                    this.refreshType=@"none";
                }
            }
        }];
        self.keys=[[self.systemNotificationData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }else{
        self.keys=[[self.systemNotificationData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }
}

-(void)loadMoreSystemNoData{
    self.refreshType=@"system";
    [SVProgressHUD dismiss];
    
    //responseData
    NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
    self.state=[NSString stringWithFormat:@"%@",tempState];
    __weak HomePageViewController *this=self;
    [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerSystemNoticeWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSArray *resultArr = responseObject[@"result"];
                    if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                        
                        if(resultArr.count!=0){
                            
                            for(int i=0;i<resultArr.count;i++){
                                SystemNoticeModel *model=[SystemNoticeModel getClassForDic:resultArr[i]];
                                if(dicM[model.createDate]==nil){
                                    NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                    [dicM setObject:arrM forKey:model.createDate];
                                }else{
                                    NSMutableArray *arrM=dicM[model.createDate];
                                    [arrM addObject:model];
                                }
                            }
                        }
                        
                    }
                }
                
//                if([responseObject isKindOfClass:[NSArray class]]){
//                    NSArray *resultArr=responseObject;
                
//                }
                this.systemNotificationData=dicM;
                this.keys=[[this.systemNotificationData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
                [this.tableView reloadData];
                this.refreshType=@"none";
                
            }
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                [SVProgressHUD showErrorWithStatus:@"网络错误"];
                this.refreshType=@"none";
                
            }
        }
    }];
}

//加载快讯播报
-(void)loadFlashNewData{
    if([self.refreshType isEqualToString:@"new"]){
        return;
    }
    [self.mjRefreshHeaderView endRefreshing];
    self.refreshType=@"new";
    if([self.flashNewData allKeys].count==0){
        
        [SVProgressHUD show];
        NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
        self.state=[NSString stringWithFormat:@"%@",tempState];
        __weak HomePageViewController *this=self;
        [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerNewsWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD dismiss];
                    NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                    
                    if ([responseObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *resultArr = responseObject[@"result"];
                        if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                            if(resultArr.count!=0){
                                
                                for(int i=0;i<resultArr.count;i++){
                                    FlashNewModel *model=[FlashNewModel getClassForDic:resultArr[i]];
                                    if(dicM[model.createDate]==nil){
                                        NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                        [dicM setObject:arrM forKey:model.createDate];
                                    }else{
                                        NSMutableArray *arrM=dicM[model.createDate];
                                        [arrM addObject:model];
                                    }
                                }
                            }
                        }
                    }
                    
//                    if([responseObject isKindOfClass:[NSArray class]]){
//                        NSArray *resultArr=responseObject;
                    
//                    }
                    
                    this.flashNewData=dicM;
                    this.keys=[[self.flashNewData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
                    this.tableView.contentOffset=CGPointMake(0, 0);
                    [this.tableView reloadData];
                    this.refreshType=@"none";
                }
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [SVProgressHUD showErrorWithStatus:@"网络错误"];
                    this.refreshType=@"none";
                }
            }
        }];
        
        //responseData
        self.keys=[[self.flashNewData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }else{
        self.keys=[[self.flashNewData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }


}

-(void)loadMoreFlashNewData{
    self.refreshType=@"new";
    [SVProgressHUD dismiss];
    //responseData
    NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
    self.state=[NSString stringWithFormat:@"%@",tempState];
    __weak HomePageViewController *this=self;
    [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerNewsWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSArray *resultArr = responseObject[@"result"];
                    if (resultArr!=nil&&[resultArr isKindOfClass:[NSArray class]]) {
                        if(resultArr.count!=0){
                            
                            for(int i=0;i<resultArr.count;i++){
                                FlashNewModel *model=[FlashNewModel getClassForDic:resultArr[i]];
                                if(dicM[model.createDate]==nil){
                                    NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                    [dicM setObject:arrM forKey:model.createDate];
                                }else{
                                    NSMutableArray *arrM=dicM[model.createDate];
                                    [arrM addObject:model];
                                }
                            }
                        }

                        
                        
                    }
                }
//                if([responseObject isKindOfClass:[NSArray class]]){
//                    NSArray *resultArr=responseObject;
//                    if(resultArr.count!=0){
//                        
//                        for(int i=0;i<resultArr.count;i++){
//                            FlashNewModel *model=[FlashNewModel getClassForDic:resultArr[i]];
//                            if(dicM[model.createDate]==nil){
//                                NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
//                                [dicM setObject:arrM forKey:model.createDate];
//                            }else{
//                                NSMutableArray *arrM=dicM[model.createDate];
//                                [arrM addObject:model];
//                            }
//                        }
//                    }
//                }
                
                this.flashNewData=dicM;
                this.keys=[[this.flashNewData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
                [this.tableView reloadData];
                this.refreshType=@"none";
            }
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        if(this){
            if([this.state isEqualToString:tempState]){
                [self.mjRefreshHeaderView endRefreshing];
                [SVProgressHUD showErrorWithStatus:@"网络错误"];
                this.refreshType=@"none";
            }
        }
    }];
}

//加载我的信息
-(void)loadMyInfoData{
    if([self.refreshType isEqualToString:@"myInfo"]){
        return;
    }
    [self.mjRefreshHeaderView endRefreshing];
    self.refreshType=@"myInfo";
    if([self.myInfoData allKeys].count==0){
        ModelUser *modeluser = [UserInfoManager sharedManager].modelMser;
        
        if(modeluser.groupCode.length!=0){
            
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            //responseData
            NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
            self.state=[NSString stringWithFormat:@"%@",tempState];
            __weak HomePageViewController *this=self;
            [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerGetVNoticesByGroupCodeWithGroupCode:modeluser.groupCode success:^(NSHTTPURLResponse *response, id responseObject) {
                if(this){
                    if([this.state isEqualToString:tempState]){
                        [SVProgressHUD dismiss];
                        NSArray *resultArr=responseObject[@"result"];
                        NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                        if(![resultArr isKindOfClass:[NSNull class]]){
                            if(resultArr.count!=0){
                                
                                for(int i=0;i<resultArr.count;i++){
                                    MyInfoModel *model=[MyInfoModel getClassForDic:resultArr[i]];
                                    if(dicM[model.sendDate]==nil){
                                        NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                        [dicM setObject:arrM forKey:model.sendDate];
                                    }else{
                                        NSMutableArray *arrM=dicM[model.sendDate];
                                        [arrM addObject:model];
                                    }
                                }
                            }
                        }
                        this.myInfoData=dicM;
                        this.keys=[[this.myInfoData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
                        this.tableView.contentOffset=CGPointMake(0, 0);
                        [this.tableView reloadData];
                        this.refreshType=@"none";
                    }
                }

            } failure:^(NSHTTPURLResponse *response, NSError *error) {
                if(this){
                    if([this.state isEqualToString:tempState]){
                        [SVProgressHUD showErrorWithStatus:@"网络错误"];
                        this.refreshType=@"none";
                    }
                }
            }];
            this.keys=[[this.myInfoData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
            this.tableView.contentOffset=CGPointMake(0, 0);
            [this.tableView reloadData];
        }else{
            self.keys=@[];
            self.tableView.contentOffset=CGPointMake(0, 0);
            [self.tableView reloadData];
            
            __weak HomePageViewController *this=self;
            self.refreshType=@"none";
            [[UserInfoManager sharedManager]presentLoginViewController:self andIsLogin:^{
                [this loadMyInfoData];
            }];
        }
    }else{
        self.keys=[[self.myInfoData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
        self.tableView.contentOffset=CGPointMake(0, 0);
        [self.tableView reloadData];
    }
}

-(void)loadMoreMyInfoData{
    self.refreshType=@"myInfo";
    [SVProgressHUD dismiss];
    ModelUser *modeluser = [UserInfoManager sharedManager].modelMser;
    
    if(modeluser.groupCode.length!=0){
        //responseData
        NSString *tempState=[NSString stringWithFormat:@"%d",[self.state intValue]+1];
        self.state=[NSString stringWithFormat:@"%@",tempState];
        __weak HomePageViewController *this=self;
        [[BuaatVolunteerServerSDK sharedInstance]requestVolunteerGetVNoticesByGroupCodeWithGroupCode:modeluser.groupCode success:^(NSHTTPURLResponse *response, id responseObject) {
                if(this){
                    if([this.state isEqualToString:tempState]){
                        [self.mjRefreshHeaderView endRefreshingWithoutIdle];
                        NSArray *resultArr=responseObject[@"result"];
                        NSMutableDictionary *dicM=[[NSMutableDictionary alloc]init];
                        if(resultArr.count!=0){
                            
                            for(int i=0;i<resultArr.count;i++){
                                MyInfoModel *model=[MyInfoModel getClassForDic:resultArr[i]];
                                if(dicM[model.sendDate]==nil){
                                    NSMutableArray *arrM=[[NSMutableArray alloc]initWithObjects:model, nil];
                                    [dicM setObject:arrM forKey:model.sendDate];
                                }else{
                                    NSMutableArray *arrM=dicM[model.sendDate];
                                    [arrM addObject:model];
                                }
                            }
                        }
                        this.myInfoData=dicM;
                        this.keys=[[this.myInfoData allKeys] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO]]];
//                        this.tableView.contentOffset=CGPointMake(0, 0);
                        [this.tableView reloadData];
                        this.refreshType=@"none";
                    }
                }
            } failure:^(NSHTTPURLResponse *response, NSError *error) {
            if(this){
                if([this.state isEqualToString:tempState]){
                    [self.mjRefreshHeaderView endRefreshing];
                    [SVProgressHUD showErrorWithStatus:@"网络错误"];
                    this.refreshType=@"none";
                }
            }
        }];
    }else{
        self.keys=@[];
        [self.mjRefreshHeaderView endRefreshing];
        [self.tableView reloadData];
        
        __weak HomePageViewController *this=self;
        [[UserInfoManager sharedManager]presentLoginViewController:self andIsLogin:^{
            [this loadMyInfoData];
        }];
    }
}

-(void)setIsNeedShowPositionResult:(BOOL)isNeedShowPositionResult{
    _isNeedShowPositionResult=isNeedShowPositionResult;
    if(_isNeedShowPositionResult==NO){
        [self.locService stopUserLocationService];
    }
}

#pragma mark - startUpdatingLocation

-(void)startUpdatingLocation{
    self.isNeedShowPositionResult=YES;
    
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"cityPosition" ofType:@"plist"];
    NSDictionary *dic=[[NSDictionary alloc]initWithContentsOfFile:filePath];
    
    self.positionCitys=dic;
    
    if ([CLLocationManager locationServicesEnabled]){
        NSLog(@"定位服务正常！");
        //        [BMKLocationServicesetLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
        //指定最小距离更新(米)，默认：kCLDistanceFilterNone
        //        [BMKLocationServicesetLocationDistanceFilter:100.f];
        
        //初始化BMKLocationService
        if(self.locService==nil){
            self.locService = [[BMKLocationService alloc]init];
            self.locService.delegate = self;
        }
        //启动LocationService
        [self.locService startUserLocationService];
        
        if(self.geoCodeSearch==nil){
            self.geoCodeSearch=[[BMKGeoCodeSearch alloc]init];
            self.geoCodeSearch.delegate=self;
        }
        
    }else{
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *str=[[NSString alloc]initWithFormat:@"请打开系统设备中“隐私-定位服务”，允许“%@”使用您的位置",infoDictionary[@"CFBundleDisplayName"]];
        
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        NSLog(@"定位服务异常");
    }
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [self.locService stopUserLocationService];
    if(self.isNeedShowPositionResult){
        
        if(self.geoCodeSearch==nil){
            self.geoCodeSearch=[[BMKGeoCodeSearch alloc]init];
            self.geoCodeSearch.delegate=self;
        }
        
        BMKReverseGeoCodeOption *option=[[BMKReverseGeoCodeOption alloc]init];
        option.reverseGeoPoint=userLocation.location.coordinate;
        [self.geoCodeSearch reverseGeoCode:option];
    }
    
}

- (void)didFailToLocateUserWithError:(NSError *)error{
    [self.locService stopUserLocationService];

    self.geoCodeSearch.delegate=nil;
    self.geoCodeSearch=nil;
//    [self.locService stopUserLocationService];

    //    [SVProgressHUD showErrorWithStatus:@"定位失败"];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if(self.isNeedShowPositionResult){
        searcher.delegate=nil;
        self.geoCodeSearch=nil;
        
        if(error!=BMK_SEARCH_NO_ERROR){
            //        [SVProgressHUD showErrorWithStatus:@"定位失败"];
            return;
        }
        NSLog(@"province=%@",result.addressDetail.province);
        NSLog(@"city=%@",result.addressDetail.city);
        NSLog(@"district=%@",result.addressDetail.district);
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            if(result.address.length!=0&&result.addressDetail.city.length!=0&&result.addressDetail.district.length!=0){
                NSMutableString *pinyin = [[NSMutableString alloc] initWithString:result.addressDetail.city];
                if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformMandarinLatin, NO)) {
                }
                if (CFStringTransform((__bridge CFMutableStringRef)pinyin, 0, kCFStringTransformStripDiacritics, NO)) {
                }
                NSString *key=[[pinyin substringWithRange:NSMakeRange(0, 1)] uppercaseString];
                NSArray *arr=self.positionCitys[key];
                NSMutableString *strM=[[NSMutableString alloc]initWithString:result.addressDetail.city];
                if([strM hasSuffix:@"市"]){
                    [strM deleteCharactersInRange:NSMakeRange(strM.length-1, 1)];
                }
                NSString *preStr=[NSString stringWithFormat:@"name LIKE[cd] '*%@*'",strM];
                NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
                NSArray *resultArr=[arr filteredArrayUsingPredicate:pre];
                if(resultArr.count!=0){
                    NSMutableDictionary *dicM=[[NSMutableDictionary alloc]initWithDictionary:[resultArr lastObject]];
                    [dicM setValue:result.addressDetail.district forKey:@"ext"];
                    
                    NSDictionary *dic=dicM;
                    self.positionState=@"city";
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:dic[@"name"] style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
                        self.navigationItem.leftBarButtonItem=leftBarButton;
                    });
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(self.districtView==nil){
                            self.districtView=[[[NSBundle mainBundle] loadNibNamed:@"DistrictView" owner:self options:nil]lastObject];
                            self.districtView.frame=CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-49);
                            [self.view addSubview:self.districtView];
                            self.districtView.delegate=self;
                            self.districtView.hidden=YES;
                        }
                        self.districtView.lastSelectedIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
                        
                        if(dic[@"a"]){
                            self.districtView.dic=dic;
                            self.districtView.data=dic[@"a"];
                        }else{
                            self.districtView.dic=dic;
                            self.districtView.data=dic[@"c"];
                        }
                        [self.districtView refreshHeightOfDistrictView];
                        self.districtView.cityLabelText=dic[@"name"];
                    });
                    
                    //        self.districtView.hidden=NO;
                    
                    //定位
                    NSString *ext=dic[@"ext"];
                    NSMutableString *strM=[[NSMutableString alloc]initWithString:ext];
                    if([strM hasSuffix:@"区"]||[strM hasSuffix:@"县"]||[strM hasSuffix:@"市"]){
                        [strM deleteCharactersInRange:NSMakeRange(strM.length-1, 1)];
                    }
                    NSArray *resultArr=nil;
                    if(dic[@"a"]){
                        NSString *preStr=[NSString stringWithFormat:@"s LIKE[cd] '*%@*'",strM];
                        NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
                        resultArr=[dic[@"a"] filteredArrayUsingPredicate:pre];
                    }else{
                        NSString *preStr=[NSString stringWithFormat:@"n LIKE[cd] '*%@*'",strM];
                        NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
                        resultArr=[dic[@"c"] filteredArrayUsingPredicate:pre];
                    }
                    if(resultArr.count!=0){
                        NSDictionary *resultDic=[resultArr lastObject];
                        int i=(int)[self.districtView.data indexOfObject:resultDic]+1;
                        NSString *name=nil;
                        if(resultDic[@"n"]){
                            name=resultDic[@"n"];
                        }else{
                            name=resultDic[@"s"];
                        }
                        self.positionState=@"city";
                        dispatch_async(dispatch_get_main_queue(), ^{
                            UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:name style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
                            self.navigationItem.leftBarButtonItem=leftBarButton;
                            self.districtView.lastSelectedIndexPath=[NSIndexPath indexPathForRow:i inSection:0];
                            
                            
                            [[NSUserDefaults standardUserDefaults]setObject:name forKey:KUserPosition];
                            [[NSUserDefaults standardUserDefaults]synchronize];
                            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationUserPositionDidChange object:nil];
                            


                        });
                        //                dispatch_after(0.2, dispatch_get_main_queue(), ^{
                        //                    [self.districtView.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
                        //                });
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.districtView.collectionView reloadData];
                    });
                }
            }
        });
    }
    
}

#pragma mark - CityPositionExtViewControllerDelegate
-(void)cityPositionExtViewController:(CityPostionExtViewController *)vc indexPath:(NSIndexPath *)indexPath positionDic:(NSDictionary *)dic{
    [vc dismissViewControllerAnimated:YES completion:nil];
    self.positionState=@"city";
    self.isNeedShowPositionResult=NO;
    UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:dic[@"name"] style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
    self.navigationItem.leftBarButtonItem=leftBarButton;
    
    [[NSUserDefaults standardUserDefaults]setObject:dic[@"name"] forKey:KUserPosition];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:NotificationUserPositionDidChange object:nil];
    if(self.districtView==nil){
        self.districtView=[[[NSBundle mainBundle] loadNibNamed:@"DistrictView" owner:self options:nil]lastObject];
        self.districtView.frame=CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-49);
        [self.view addSubview:self.districtView];
        self.districtView.delegate=self;
        self.districtView.hidden=YES;
    }
    self.districtView.hidden=NO;
    if(dic[@"a"]){
        self.districtView.dic=dic;
        self.districtView.data=dic[@"a"];
    }else{
        self.districtView.dic=dic;
        self.districtView.data=dic[@"c"];
    }
    [self.districtView refreshHeightOfDistrictView];
    self.districtView.cityLabelText=dic[@"name"];
    if(indexPath.section==0){
        //定位
        NSString *ext=dic[@"ext"];
        NSMutableString *strM=[[NSMutableString alloc]initWithString:ext];
        if([strM hasSuffix:@"区"]||[strM hasSuffix:@"县"]||[strM hasSuffix:@"市"]){
            [strM deleteCharactersInRange:NSMakeRange(strM.length-1, 1)];
        }
        
        NSArray *resultArr=nil;
        if(dic[@"a"]){
            NSString *preStr=[NSString stringWithFormat:@"s LIKE[cd] '*%@*'",strM];
            NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
            resultArr=[dic[@"a"] filteredArrayUsingPredicate:pre];
        }else{
            NSString *preStr=[NSString stringWithFormat:@"n LIKE[cd] '*%@*'",strM];
            NSPredicate *pre=[NSPredicate predicateWithFormat:preStr];
            resultArr=[dic[@"c"] filteredArrayUsingPredicate:pre];
        }
        if(resultArr.count!=0){
            NSDictionary *resultDic=[resultArr lastObject];
            int i=(int)[self.districtView.data indexOfObject:resultDic]+1;
            NSString *name=nil;
            if(resultDic[@"n"]){
                name=resultDic[@"n"];
            }else{
                name=resultDic[@"s"];
            }
            UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:name style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
            self.navigationItem.leftBarButtonItem=leftBarButton;
            self.districtView.lastSelectedIndexPath=[NSIndexPath indexPathForRow:i inSection:0];
            [self.districtView.collectionView reloadData];
            
            
            [[NSUserDefaults standardUserDefaults]setObject:name forKey:KUserPosition];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [[NSNotificationCenter defaultCenter]postNotificationName:NotificationUserPositionDidChange object:nil];
            
        }
        return;
    }
    if(indexPath.section==1){
        //热门
    }
    self.districtView.lastSelectedIndexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.districtView.collectionView reloadData];
//    dispatch_after(0.2, dispatch_get_main_queue(), ^{
//        [self.districtView.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//    });
    
}

#pragma mark - DistrictView
-(void)districtView:(DistrictView *)view indexPath:(NSIndexPath *)indexPath positionDic:(NSDictionary *)dic{
    self.districtView.hidden=YES;
    if(indexPath.section==0){
        self.positionState=@"district";
        UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:dic[@"name"] style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
        self.navigationItem.leftBarButtonItem=leftBarButton;
        
        
        /////定位保存
        [[NSUserDefaults standardUserDefaults]setObject:dic[@"name"] forKey:KUserPosition];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationUserPositionDidChange object:nil];
        
        return;
    }
    if(indexPath.section==1){
        CityPostionExtViewController *vc=[[CityPostionExtViewController alloc]init];
        vc.delegate=self;
        BaseNavigationController *nav=[[BaseNavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    
}

#pragma mark - LeftBarButton
-(void)chickLeftBarButton:(UIBarButtonItem *)sender{
    self.isNeedShowPositionResult=NO;
    
    [self.locService stopUserLocationService];
    self.locService=nil;
    self.geoCodeSearch.delegate=nil;
    self.geoCodeSearch=nil;
    
    
    if(self.positionState.length==0){
        CityPostionExtViewController *vc=[[CityPostionExtViewController alloc]init];
        vc.delegate=self;
        BaseNavigationController *nav=[[BaseNavigationController alloc]initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        self.districtView.hidden=!self.districtView.hidden;
    }
    
}

#pragma mark - tableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(self.tag!=0){
        if(indexPath.row==0){
            return;
        }
    }
    NSString *noticeTitle=@"";
    NSString *title=@"";
    NSString *urlStr=nil;
    switch (self.tag) {
        case 0:{
            id model=self.allData[indexPath.row];
            if([model isKindOfClass:[SystemNoticeModel class]]){
                title=@"系统通知";
                urlStr=((SystemNoticeModel *)model).link;
                noticeTitle=((SystemNoticeModel *)model).noticeTitle;
            }else if ([model isKindOfClass:[FlashNewModel class]]){
                title=@"快讯播报";
                urlStr=((FlashNewModel *)model).link;
                noticeTitle=((FlashNewModel *)model).noticeTitle;
            }
        }
            break;
        case 1:{
            title=@"系统通知";
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.systemNotificationData[key];
            SystemNoticeModel *model=arr[indexPath.row-1];
            urlStr=model.link;
            noticeTitle=model.noticeTitle;
        }
            break;
        case 2:{
            title=@"快讯播报";
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.flashNewData[key];
            FlashNewModel *model=arr[indexPath.row-1];
            urlStr=model.link;
            noticeTitle=model.noticeTitle;
        }
            break;
        case 3:{
            title=@"我的信息";
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.myInfoData[key];
            MyInfoModel *model=arr[indexPath.row-1];
            if([model.noticeContentUrl isKindOfClass:[NSString class]]&&model.noticeContentUrl.length!=0){
                urlStr=model.noticeContentUrl;
            }else{
                urlStr=@"";
            }
            noticeTitle=model.noticeTitle;
        }
            break;
        default:
            break;
    }
    InfoDetailViewController *vc=[[InfoDetailViewController alloc]init];
    vc.title=title;
    vc.urlStr=urlStr;
    vc.noticeTitle=noticeTitle;
    [self.navigationController pushViewController:vc animated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (self.tag) {
        case 0:{
            return self.allData.count;
        }
            break;
        case 1:{
            NSArray *key=self.keys[section];
            NSArray *arr=self.systemNotificationData[key];
            return arr.count+1;
        }
            break;
        case 2:{
            NSArray *key=self.keys[section];
            NSArray *arr=self.flashNewData[key];
            return arr.count+1;
        }
            break;
        case 3:{
            NSArray *key=self.keys[section];
            NSArray *arr=self.myInfoData[key];
            return arr.count+1;
        }
            break;
        default:
            break;
    }
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *HomePageSectionHeaderCellTableViewCellIdentifier=@"HomePageSectionHeaderCellTableViewCellIdentifier";
    switch (self.tag) {
        case 0:{
            //所有
            static NSString *HomeAllNewInfoTableViewCellIdentifier=@"HomeAllNewInfoTableViewCellIdentifier";
            static NSString *HomeAllSystemNoticeTableViewCellIdentifier=@"HomeAllSystemNoticeTableViewCellIdentifier";
            UITableViewCell *cell=nil;
            id model=self.allData[indexPath.row];
            if([model isKindOfClass:[SystemNoticeModel class]]){
                HomeAllSystemNoticeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HomeAllSystemNoticeTableViewCellIdentifier forIndexPath:indexPath];
                cell.titleLabel.text=((SystemNoticeModel *)model).noticeTitle;
                cell.dateLabel.text=((SystemNoticeModel *)model).createDate;
                
                return cell;
            }else if ([model isKindOfClass:[FlashNewModel class]]){
                HomeAllNewInfoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HomeAllNewInfoTableViewCellIdentifier forIndexPath:indexPath];
                cell.titleLabel.text=((FlashNewModel *)model).noticeTitle;
                cell.dateLabel.text=((FlashNewModel *)model).createDate;
                if(((FlashNewModel *)model).imgaeUrl){
                    cell.titleLabelWidth.constant=SCREEN_WIDTH-202;
                    cell.rightImageView.hidden=NO;
                    [cell.rightImageView sd_setImageWithURL:[NSURL URLWithString:((FlashNewModel *)model).imgaeUrl]];
                }else{
                    cell.titleLabelWidth.constant=SCREEN_WIDTH-14-8;
                    cell.rightImageView.hidden=YES;
                }
                return cell;
                
            }else if ([model isKindOfClass:[MyInfoModel class]]){
                cell=[tableView dequeueReusableCellWithIdentifier:HomeAllNewInfoTableViewCellIdentifier forIndexPath:indexPath];
                
            }
            return cell;
        }
            break;
        case 1:{
            //系统通知
            if(indexPath.row==0){
                NSString *key=self.keys[indexPath.section];
                HomePageSectionHeaderCellTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HomePageSectionHeaderCellTableViewCellIdentifier forIndexPath:indexPath];
                [self handleSectionHeaderCellTableViewCell:cell key:key];
                return cell;
            }
            
            static NSString * SystemNotificationTableViewCellIdentifier=@"SystemNotificationTableViewCellIdentifier";
            SystemNotificationTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SystemNotificationTableViewCellIdentifier forIndexPath:indexPath];
            
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.systemNotificationData[key];
            
            if(arr.count==1&&self.keys.count==1){
                cell.topLineView.hidden=YES;
                cell.bottomLineView.hidden=YES;
                cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);

            }else{
                if(indexPath.row==1&&indexPath.section==0){
                    cell.topLineView.hidden=YES;
                    cell.bottomLineView.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                    
                }else if (indexPath.row-1==arr.count-1&&indexPath.section==self.keys.count-1){
                    cell.topLineView.hidden=NO;
                    cell.bottomLineView.hidden=YES;
                    cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
                }else{
                    cell.topLineView.hidden=NO;
                    cell.bottomLineView.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                    
                }
            }
            
            
            SystemNoticeModel *model=arr[indexPath.row-1];
            cell.contentLabel.text=model.noticeTitle;
            return cell;
        }
            break;
        case 2:{
            //快讯播报
            if(indexPath.row==0){
                NSString *key=self.keys[indexPath.section];
                HomePageSectionHeaderCellTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HomePageSectionHeaderCellTableViewCellIdentifier forIndexPath:indexPath];
                [self handleSectionHeaderCellTableViewCell:cell key:key];
                return cell;
            }

            static NSString *FlashNewTableViewCellIdentifier=@"FlashNewTableViewCellIdentifier";
            NewsInfoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:FlashNewTableViewCellIdentifier forIndexPath:indexPath];
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.flashNewData[key];
            
            if(arr.count==1&&self.keys.count==1){
                cell.upLine.hidden=YES;
                cell.doneLine.hidden=YES;
                cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
            }else{
                if(indexPath.row==1&&indexPath.section==0){
                    cell.upLine.hidden=YES;
                    cell.doneLine.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                    
                }else if (indexPath.row-1==arr.count-1&&indexPath.section==self.keys.count-1){
                    cell.upLine.hidden=NO;
                    cell.doneLine.hidden=YES;
                    cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
                }else{
                    cell.upLine.hidden=NO;
                    cell.doneLine.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                }
            }
            
            FlashNewModel *model=arr[indexPath.row-1];
            if(model.noticeTitle.length!=0){
                cell.titleLabel.text=model.noticeTitle;
            }
            if(model.imgaeUrl){
                cell.titleLabelWidth.constant=SCREEN_WIDTH-32-104;
                cell.rightIamgeView.hidden=NO;
                [cell.rightIamgeView sd_setImageWithURL:[NSURL URLWithString:model.imgaeUrl]];
            }else{
                cell.titleLabelWidth.constant=SCREEN_WIDTH-32-8;
                cell.rightIamgeView.hidden=YES;
            }
            return cell;
        }
            break;
        case 3:{
            //我的信息
            if(indexPath.row==0){
                NSString *key=self.keys[indexPath.section];
                HomePageSectionHeaderCellTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:HomePageSectionHeaderCellTableViewCellIdentifier forIndexPath:indexPath];
                [self handleSectionHeaderCellTableViewCell:cell key:key];
                return cell;
            }
            static NSString *FlashNewTableViewCellIdentifier=@"FlashNewTableViewCellIdentifier";
            NewsInfoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:FlashNewTableViewCellIdentifier forIndexPath:indexPath];
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.myInfoData[key];
            MyInfoModel *myInfo=arr[indexPath.row-1];
            
            if(arr.count==1&&self.keys.count==1){
                cell.upLine.hidden=YES;
                cell.doneLine.hidden=YES;
                cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
            }else{
                if(indexPath.row==1&&indexPath.section==0){
                    cell.upLine.hidden=YES;
                    cell.doneLine.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                    
                }else if (indexPath.row-1==arr.count-1&&indexPath.section==self.keys.count-1){
                    cell.upLine.hidden=NO;
                    cell.doneLine.hidden=YES;
                    cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
                }else{
                    cell.upLine.hidden=NO;
                    cell.doneLine.hidden=NO;
                    cell.separatorInset=UIEdgeInsetsMake(0, 21, 0, 0);
                    
                }
            }
            
            
            if(myInfo.noticeTitle.length!=0){
                cell.titleLabel.text=myInfo.noticeTitle;
            }
            [cell.rightIamgeView sd_setImageWithURL:[NSURL URLWithString:showDefaultImageUrl]];
            return cell;
        }
            break;
        default:
            break;
    }
    return nil;
}

-(void)handleSectionHeaderCellTableViewCell:(HomePageSectionHeaderCellTableViewCell *)cell key:(NSString *)key{
    NSDate *date=nil;
    if(key.length==8+6+1){
        //我的信息
        cell.dateLabel.text=[[NSString alloc]initWithFormat:@"%@-%@-%@",[key substringWithRange:NSMakeRange(0, 4)],[key substringWithRange:NSMakeRange(4, 2)],[key substringWithRange:NSMakeRange(6, 2)]];
        NSDateFormatter *f=[[NSDateFormatter alloc]init];
        [f setDateFormat:@"yyyyMMddHHmmss"];
        date=[f dateFromString:key];
    }else{
        key=[[NSString alloc]initWithFormat:@"%@-%@-%@",[key substringWithRange:NSMakeRange(0, 4)],[key substringWithRange:NSMakeRange(4, 2)],[key substringWithRange:NSMakeRange(6, 2)]];
        cell.dateLabel.text=key;
        key=[NSString stringWithFormat:@"%@ 00:00:00",key];
        NSDateFormatter *f=[[NSDateFormatter alloc]init];
        [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        date=[f dateFromString:key];
    }
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
    int week = [componets weekday];
    NSString *result=nil;
    switch (week) {
        case 2:{
            result=@"星期一";
        }
            break;
        case 3:{
            result=@"星期二";
        }
            break;
        case 4:{
            result=@"星期三";
        }
            break;
        case 5:{
            result=@"星期四";
        }
            break;
        case 6:{
            result=@"星期五";
        }
            break;
        case 7:{
            result=@"星期六";
        }
            break;
        case 1:{
            result=@"星期日";
        }
            break;
        default:
            break;
    }
    cell.weekLabel.text=result;
    
    double interval;
    NSDate *todayDate=[NSDate date];
    result=nil;
    interval=[todayDate timeIntervalSinceDate:date];
    if(interval>0){
        if(interval<24*60*60){
            result=@"今天";
        }else if (interval<2*24*60*60){
            result=@"昨天";
        }else if (interval<3*24*60*60){
            result=@"前天";
        }else{
            result=nil;
        }
    }
    if(result==nil){
        cell.dayLabel.text=@"";
    }else{
        cell.dayLabel.text=result;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (self.tag) {
        case 0:{
            //全部
            return [self getHeightOfAllCellWith:indexPath];
        }
            break;
        case 1:{
            //系统通知
            if(indexPath.row==0){
                return 24.0f;
            }
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.systemNotificationData[key];
            return [self getHeightOfSystemNotiCellWith:arr[indexPath.row-1]];
        }
            break;
        case 2:{
            //快讯播报
            if(indexPath.row==0){
                return 25.0f;
            }
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.flashNewData[key];
            return [self getHeightOfNewsInfoCellWith:arr[indexPath.row-1]];
        }
            break;
        case 3:{
            //我的信息
            if(indexPath.row==0){
                return 25.0f;
            }
            NSString *key=self.keys[indexPath.section];
            NSArray *arr=self.myInfoData[key];
            return [self getHeightOfMyInfoCellWith:arr[indexPath.row-1]];
        }
            break;
        default:
            break;
    }
    return 0;
}

-(CGFloat)getHeightOfAllCellWith:(NSIndexPath *)indexPath{
    id model=self.allData[indexPath.row];
    if([model isKindOfClass:[SystemNoticeModel class]]){
        return [self getHeightOfAllSystemNotiCellWith:(SystemNoticeModel *)model];
    }else if ([model isKindOfClass:[FlashNewModel class]]){
        return [self getHeightOfAllNewInfoCellWith:(FlashNewModel *)model];
    }else if ([model isKindOfClass:[MyInfoModel class]]){
        return [self getHeightOfAllNewInfoCellWith:(MyInfoModel *)model];
    }
    return 0;
}

-(CGFloat)getHeightOfAllSystemNotiCellWith:(SystemNoticeModel *)model{
    float height=0;
    NSString *title=model.noticeTitle;
    height+=4+21+3+8;
    height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-14-14]+5;
    return height;
}

-(CGFloat)getHeightOfAllNewInfoCellWith:(id)model{
    float height=0;
    NSString *title=((FlashNewModel *)model).noticeTitle;
    height+=6+8;
    if(((FlashNewModel *)model).imgaeUrl){
        height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-202]+5;
    }else{
        height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-14-8]+5;
    }
    if(height<60+6+8){
        height=60+6+8;
    }
    return height;
}

-(CGFloat)getHeightOfSystemNotiCellWith:(SystemNoticeModel *)model{
    float height=0;
    NSString *title=model.noticeTitle;
    height+=10+9;
    height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-20-34]+5;
    return height;
}

-(CGFloat)getHeightOfNewsInfoCellWith:(FlashNewModel *)model{
    float height=0;
    NSString *title=model.noticeTitle;
    height+=6+8;
    if(model.imgaeUrl){
        height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-136]+5;
    }else{
        height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-32-8]+5;
    }
    if(height<60+6+8){
        height=60+6+8;
    }
    return height;
}

-(CGFloat)getHeightOfMyInfoCellWith:(MyInfoModel *)model{
    float height=0;
    NSString *title=model.noticeTitle;
    height+=4+21+3+8;
    height+=[Utils heightForLabel:title andFont:15.0f andWidth:SCREEN_WIDTH-136]+5;
    if(height<76){
        height=76;
    }
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    switch (tableView.tag-100) {
        case 0:{
            //全部
        }
            break;
        case 1:{
            //系统通知
        }
            break;
        case 2:{
            //快讯播报
        }
            break;
        case 3:{
            //我的信息
        }
            break;
        default:
            break;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.keys.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(self.tag==0){
        return nil;
    }
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,25)];
    view.backgroundColor=[UIColor colorWithRed:244/255.0 green:245/255.0 blue:246/255.0 alpha:1];
    NSString *key=self.keys[section];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(14, 0, 75, view.height)];
    label.font=[UIFont systemFontOfSize:12.0f];
    label.textColor=[UIColor colorWithRed:128/255.0 green:129/255.0 blue:130/255.0 alpha:1];
    label.text=key;
    [view addSubview:label];
    
    key=[NSString stringWithFormat:@"%@ 00:00:00",key];
    NSDateFormatter *f=[[NSDateFormatter alloc]init];
    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[f dateFromString:key];
    NSDateComponents *componets = [[NSCalendar autoupdatingCurrentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
    int week = [componets weekday];
    label=[[UILabel alloc]initWithFrame:CGRectMake(label.x+label.width, 0, 60, view.height)];
    label.font=[UIFont systemFontOfSize:12.0f];
    label.textColor=[UIColor colorWithRed:128/255.0 green:129/255.0 blue:130/255.0 alpha:1];
    NSString *result=nil;
    switch (week) {
        case 2:{
            result=@"星期一";
        }
            break;
        case 3:{
            result=@"星期二";
        }
            break;
        case 4:{
            result=@"星期三";
        }
            break;
        case 5:{
            result=@"星期四";
        }
            break;
        case 6:{
            result=@"星期五";
        }
            break;
        case 7:{
            result=@"星期六";
        }
            break;
        case 1:{
            result=@"星期日";
        }
            break;
        default:
            break;
    }
    label.textAlignment=NSTextAlignmentLeft;
    label.text=result;
    [view addSubview:label];
    
    double interval;
    NSDate *todayDate=[NSDate date];
    result=nil;
    interval=[todayDate timeIntervalSinceDate:date];
    if(interval>0){
        if(interval<24*60*60){
            result=@"今天";
        }else if (interval<2*24*60*60){
            result=@"昨天";
        }else if (interval<3*24*60*60){
            result=@"前天";
        }else{
            result=nil;
        }
    }
    
    label=[[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-25-14, 0, 25, view.height)];
    if(result==nil){
        label.text=@"";
    }else{
        label.text=result;
    }
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor=[UIColor colorWithRed:128/255.0 green:129/255.0 blue:130/255.0 alpha:1];
    label.font=[UIFont systemFontOfSize:10.0f];
    [view addSubview:label];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

#pragma mark - AdScrollView
-(void)adScrollView:(AdScrollView *)adScrollView tapImageViewWithIndex:(NSInteger)index urlStr:(NSString *)urlStr{
    HomeWebViewController *vc=[[HomeWebViewController alloc]init];
    vc.urlStr=urlStr;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - MJRefreshBaseView delegate
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    switch (self.tag) {
        case 0:{
            //全部
            [self loadMoreAllData];
        }
            break;
        case 1:{
            //系统通知
            [self loadMoreSystemNoData];
        }
            break;
        case 2:{
            //快讯播报
            [self loadMoreFlashNewData];
        }
            break;
        case 3:{
            //我的信息
            [self loadMoreMyInfoData];
        }
            break;
        default:
            break;
    }

}

-(void)userPositionDidChange:(NSNotification *)sender{
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults]valueForKey:KUserPosition]);
    [self netLoadAd];
}
@end
